package com.wang.helloworld.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class StandaloneEhcache {
	static CacheManager cchm = CacheManager.getInstance();
	Cache cch;
	String cacheName;
	
	protected void getCacheManager()
	{
		if(null == cchm)
		{
			cchm = CacheManager.getInstance();
		}
	}
	
	public StandaloneEhcache(String cacheName)
	{
		getCacheManager();

		this.cacheName = cacheName;
        cchm.addCache(cacheName);
		cch = cchm.getCache(cacheName);
	}
	
	public Cache getCache()
	{
		return cch;
	}

	// Add key-value
	public <T> void addValue(String name, T value)
	{
		cch.put(new Element(name, value));
	}
	
	// Retrieve value from given key
	public <T> T getValue(String name)
	{
		return (T) cch.get(name);
	}
	
	public void destroy()
	{
		cchm.removeCache(cacheName);
	}
	
	protected void finalize()
	{
		destroy();
	}
}
